package ustc.xiaoyang.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import ustc.xiaoyang.pojo.Result;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    public Result handleException(Exception e){
        log.error("程序出错了",e);
        return Result.error("服务器异常");
    }
    @ExceptionHandler
    public Result handleException(DuplicateKeyException e){
        log.error("程序出错了",e);
        String message = e.getMessage();
        int i = message.lastIndexOf("Duplicate entry");
        //Duplicate entry '15898398943' for key 'emp.phone'
        String errMsg = message.substring(i);
        return Result.error(errMsg.split(" ")[2]+"已存在");
    }
    @ExceptionHandler
    public Result handleException(ClazzHasStudentException e){
        log.error("程序出错了",e);
        return Result.error(e.getMessage());
    }
    @ExceptionHandler
    public Result handleException(DeptHasEmpException e){
        log.error("程序出错了",e);
        return Result.error(e.getMessage());
    }

}
